package com.len.timedTask;

import com.len.entity.*;
import com.len.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
public class DayDataTask implements Job {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void execute(JobExecutionContext context) {
        log.info("日报任务：启动任务=======================");
        run();
        log.info("日报任务：下次执行时间====="+
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime())+"==============");
    }

    private void run() {

        long beginTime = DateUtil.getDayBegin().getTime()/1000;

        long now = System.currentTimeMillis()/1000;
        long a = DateUtil.getDayBegin().getTime()/1000-now;
        a = a>0?a:-a;
        if (a<300){
            beginTime = beginTime - (24*3600);
        }
        long endTime = beginTime + (24*3600);
        Criteria criteria;

        DayDataEntity dayDataEntity = new DayDataEntity();
        dayDataEntity.setTime(beginTime);
        //注册人数
        criteria = new Criteria();
        criteria.and("createTime").gte(beginTime).lt(endTime);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().count().as("count1")
        );
        List<StatisticsEntity> statisticsEntities = mongoTemplate.aggregate(aggregation, UserEntity.class, StatisticsEntity.class).getMappedResults();
        long total = 0L;
        if (!statisticsEntities.isEmpty()){
            StatisticsEntity statisticsEntity = statisticsEntities.get(0);
            total = statisticsEntity.getCount1();
        }
        dayDataEntity.setRegisterUserCount(total);

        //充值金额
        criteria = new Criteria();
        criteria.and("createTime").gte(beginTime).lt(endTime);
        criteria.and("status").is(1);
        aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().sum("amount").as("count1")
        );
        statisticsEntities = mongoTemplate.aggregate(aggregation, PayEntity.class, StatisticsEntity.class).getMappedResults();
        total = 0L;
        if (!statisticsEntities.isEmpty()){
            StatisticsEntity statisticsEntity = statisticsEntities.get(0);
            total = statisticsEntity.getCount1();
        }
        dayDataEntity.setRechargeAmount(total);

        //新用户充值金额
        criteria = new Criteria();
        criteria.and("createTime").gte(beginTime).lt(endTime);
        criteria.and("status").is(1);
        aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.lookup("user","userId","id","link"),
                Aggregation.unwind("link"),
                Aggregation.project("amount").and("link.createTime").as("userCreateTime"),
                Aggregation.match(Criteria.where("userCreateTime").gte(beginTime).lt(endTime)),
                Aggregation.group().sum("amount").as("count1")
        );
        statisticsEntities = mongoTemplate.aggregate(aggregation, PayEntity.class, StatisticsEntity.class).getMappedResults();
        total = 0L;
        if (!statisticsEntities.isEmpty()){
            StatisticsEntity statisticsEntity = statisticsEntities.get(0);
            total = statisticsEntity.getCount1();
        }
        dayDataEntity.setNewUserRechargeAmount(total);

        DayDataEntity dayDataEntity1 = mongoTemplate.findOne(Query.query(Criteria.where("time").is(beginTime)),DayDataEntity.class);
        if (dayDataEntity1 == null){
            mongoTemplate.insert(dayDataEntity);
        }else {
            mongoTemplate.updateFirst(
                    Query.query(
                            Criteria.where("time").is(beginTime)
                    ),
                    Update.update("registerUserCount",dayDataEntity.getRegisterUserCount()).set("rechargeAmount",dayDataEntity.getRechargeAmount()).set("newUserRechargeAmount",dayDataEntity.getNewUserRechargeAmount()),
                    DayDataEntity.class);
        }
    }
}
